<template>
    <div class="app-container">
        <!-- 用户感知管理 -->
        <health-card :numLength="2" :overviewData="overviewData" class="perception_health_card">
            <!-- 头 -->
            <template #cardTopNum>
                <overview-num-box :title="'投诉数量'">
                    <span>{{ overviewData.complaintNum }}个</span>
                </overview-num-box>
            </template>

            <!-- 底部 -->
            <template #cardItem>
                <!-- <div class="card_item">
                    <overview-num-box :title="'投诉数量'">
                        <span>{{ overviewData.complaintNum }}个</span>
                    </overview-num-box>
                </div> -->
                <div class="card_item">
                    <overview-box :title="'近一周用户感知趋势(平均分)'">
                        <qushi :chart-data="overviewData.monthAverage" />
                    </overview-box>
                </div>
                <div class="card_item">
                    <overview-box :title="'各区县用户感知平均分'">
                        <quxian :chart-data="overviewData.todayDistrictAverage" />
                    </overview-box>
                </div>
            </template>
        </health-card>

        <el-card shadow="always">
            <el-form :model="queryParams" :inline="true" label-width="100px">
                <el-form-item label="网络制式：" prop="networkType">
                    <el-select v-model="queryParams.networkType" placeholder="请选择网络制式" style="width: 240px">
                        <el-option v-for="dict in nhp_network_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属区县：" prop="county">
                    <el-select v-model="queryParams.county" placeholder="请选择所属区县" clearable style="width: 240px">
                        <el-option v-for="dict in nhp_county_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="GGI：" prop="cgi">
                    <el-input v-model="queryParams.cgi" placeholder="请输入CGI" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="小区名称：" prop="cellName">
                    <el-input v-model="queryParams.cellName" placeholder="请输入小区名称" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="创建时间：" prop="createTime">
                    <el-date-picker v-model="queryParams.createStartEnd" type="daterange" start-placeholder="开始时间"
                        end-placeholder="结束时间" :size="size" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="listPerceptionTable">查询</el-button>
                    <el-button @click="unsetQueryForm"><el-icon>
                            <RefreshRight />
                        </el-icon>重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="always" style="margin-top: 10px;min-height: 500px;padding-bottom: 3px;">
            <el-row>
                <el-button type="primary" icon="Upload" @click="importFile">导入</el-button>
                <el-button type="primary" icon="Download" @click="exportData">导出</el-button>
            </el-row>
            <div id="table" style="margin-top: 20px;">
                <el-table v-loading="loading" ref="qualityTable" :data="tableData" style="width: 100%"
                    @sort-change="sortChange">
                    <el-table-column prop="county" label="所属区县" width="100" align="center" fixed />
                    <el-table-column prop="cgi" label="CGI" width="180" align="center" fixed />
                    <el-table-column prop="cellName" label="小区名称" width="200" align="center" fixed />
                    <el-table-column prop="createTime" label="创建日期" :formatter="dateFormatter" width="120" fixed
                        align="center" />
                    <el-table-column prop="status" label="状态" width="150" align="center" fixed>
                        <template #default="scope">
                            <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'" disable-transitions>{{
                                scope.row.status
                                    == 1 ? "正常" : "异常" }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="complaintNum" label="投诉数量" width="150" align="center" sortable="custom" />
                    <el-table-column prop="satisfaction" label="用户满意度" width="150" align="center" sortable="custom" />
                    <el-table-column prop="perceptionScore" label="用户感知总分" width="150" align="center" fixed="right"
                        sortable="custom" />
                    <el-table-column fixed="right" label="操作" align="center">
                        <template #default="scope">
                            <el-button link type="primary" size="small"
                                @click="showDetailDialog(scope.row.cgi)">详情</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next" :total="total" @size-change="listPerceptionTable"
                    @current-change="listPerceptionTable" /> -->
                <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
                    @pagination="listPerceptionTable" :autoScroll="false" />
            </div>
        </el-card>

        <el-dialog v-model="dialogTableVisible" title="详情分析" width="1400" @opened="initChart">
            <el-card class="card-box" v-loading="xqLoading">
                <el-form :model="queryParams" ref="queryForm" :inline="true">
                    <el-form-item label="时间选择">
                        <el-date-picker v-model="detailDatePicker" type="daterange" style="width: 350px"
                            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" align="right"
                            @change="search"></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="detailSearch">查询</el-button>
                    </el-form-item>
                </el-form>
                <div class="card-content" style="display: flex" v-show="!showAll">
                    <div class="card-left">
                        <el-table :data="detailData" style="width: 100%" class="tableBox" max-height="500" id="tableBox"
                            @row-click="handleClickChange" :row-class-name="tableRowClassName">
                            <el-table-column prop="county" label="所属区县" width="120" align="center" />
                            <el-table-column prop="cgi" label="CGI" width="150" align="center" />
                            <el-table-column prop="cellName" label="小区名称" width="250" align="center" />
                            <el-table-column prop="createTime" label="创建时间" :formatter="dateFormatter" width="200"
                                align="center" />
                            <el-table-column prop="perceptionScore" label="用户感知总分" width="120" fixed="right"
                                align="center" />
                        </el-table>
                    </div>
                    <div class="card-right">
                        <div class="title-name">分数趋势:</div>
                        <div id="chart" style="width: 620px; height: 320px; margin: -10px 20px 20px 40px" class=""
                            ref="chart" v-show="!showAll"></div>
                        <div class="data-analyse">
                            <div class="analyse-title">数据分析：</div>
                            <div class="analyse-itemlist">
                                <div class="analyse-item">
                                    <a>所选时间：{{ selectedDays }}天</a>
                                </div>
                                <div class="analyse-item">
                                    <a>用户感知平均分：{{ averageScore.toFixed(2) }}分</a>
                                </div>
                                <div class="analyse-item">
                                    <a>所选时间内最高分：{{ maxScore }}分</a>
                                </div>
                                <div class="analyse-item">
                                    <a>所选时间内最低分:{{ minScore }}分</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>
        </el-dialog>

        <export-dialog ref="refExportDialog" @directExport="directExportData" />

        <el-dialog v-model="importDialogVisible" title="导入文件" width="400">
            <el-form label-width="120px">
                <el-form-item label="文件上传">
                    <el-upload :action="uploadFileUrl" class="upload-demo" :headers="headers"
                        :on-success="uploadSuccess" :show-file-list="false">
                        <el-button type="primary">上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="模版下载">
                    <a @click="downloadTemplate" class="download-link">满意度上传表.xlsx</a>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup name="networkPerception">

import { queryPerception4gResultList, queryPerception5gResultList, detailList, queryPerceptionOverview } from '@/api/biz/networkPerception';
import * as echarts from 'echarts';

import { useConfigStore } from "@/store/modules/config.js";

import qushi from "../chart/qushi.vue";
import quxian from "../chart/quxian.vue";
import { getToken } from '@/utils/auth'

import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance();
const { nhp_county_type, nhp_network_type } = proxy.useDict("nhp_county_type", "nhp_network_type");

const refExportDialog = ref(null)

let overviewData = ref({})

const configStoreData = useConfigStore();
let securityFlagConfig = configStoreData.configList.filter(
    (item) => item.configKey === "sys.securityFlag"
)[0];
// console.log("securityFlagConfig", securityFlagConfig);

var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);

const queryParams = ref({
    networkType: "5G",
    createStartEnd: [new Date(), currentDate],
    exportType: '工单导出'
})

const tableData = ref([])
const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)
const nowSortContent = ref()
const nowOrder = ref()

let loading = ref(false)
let xqLoading = ref(false)

const dialogTableVisible = ref(false)
const chooseRowCgi = ref()
const detailData = ref([])

const chart = ref(null);
let chartInstance = null;
const selectedDays = ref(0);
const averageScore = ref(0);
const maxScore = ref(0);
const minScore = ref(0);
const currentNetworkType = ref("5G")

// 时间选择器(默认当天往前一周)
const datePicker = ref('');
const detailDatePicker = ref('');
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
const defaultDateRange = [new Date(), currentDate];
datePicker.value = defaultDateRange;
detailDatePicker.value = [start, end];

const importDialogVisible = ref(false)

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/networkPerception/importUserSatisfaction"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });


const setTodayDistrictAverageSort = () => {
    let topThree = overviewData.value.todayDistrictAverage.map((item, index) => ({ ...item, index })).sort((a, b) => b.value - a.value).slice(0, 3)
    let lastThree = overviewData.value.todayDistrictAverage.map((item, index) => ({ ...item, index })).sort((a, b) => b.value - a.value).slice(-3)

    overviewData.value.todayDistrictAverage.push({
        topThree, lastThree,
    })
    // console.log(overviewData.value.todayDistrictAverage)

    topThree.forEach((item, index) => {
        overviewData.value.todayDistrictAverage[item.index].itemStyle = {
            color: '#92cc76'
        }
    })
    lastThree.forEach(item => {
        overviewData.value.todayDistrictAverage[item.index].itemStyle = {
            color: '#a90000'
        }
    })
}

const dataOverview = () => {
    // console.log("dataOverview");
    // 接口
    queryPerceptionOverview().then(res => {
        let data = res.data

        if (data.dateTime) {
            let current = new Date(data.dateTime).getTime() + 24 * 60 * 60 * 1000
            queryParams.value.createStartEnd = [new Date(data.dateTime), new Date(current)]
            listPerceptionTable()
        }

        let timeList = data.timeList;
        let avgScoreList = data.avgScoreList;
        let monthAverage = []
        for (let i = 0; i < timeList.length; i++) {
            var temp = {
                name: timeList[i],
                value: avgScoreList[i]
            }
            monthAverage.push(temp)
        }

        let countyList = data.countyList
        let countyAvgScoreList = data.countyAvgScoreList
        let todayDistrictAverage = []
        for (let i = 0; i < countyList.length; i++) {
            var temp = {
                name: countyList[i],
                value: countyAvgScoreList[i]
            }
            todayDistrictAverage.push(temp)
        }

        overviewData.value = {
            latestTime: formatDate(data.dateTime),
            todayAverage: data.avgScore,  // 今日平均分
            monthAverage: monthAverage,
            todayDistrictAverage: todayDistrictAverage,
            complaintNum: data.complaintNum,
        }

        setTodayDistrictAverageSort()
    })
}
dataOverview()

function listPerceptionTable() {
    const param = {}
    param.pageSize = pageSize.value
    param.pageNum = currentPage.value
    param.county = queryParams.value.county
    param.cgi = queryParams.value.cgi
    param.cellName = queryParams.value.cellName
    param.sortContent = nowSortContent.value;
    param.order = nowOrder.value;
    console.log(queryParams.value.createStartEnd);
    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
        param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
    }
    loading.value = true
    if (queryParams.value.networkType == "5G") {
        //加载5G结果
        queryPerception5gResultList(param).then(res => {
            loading.value = false
            tableData.value = res.rows;
            total.value = res.total;
        })

    } else if (queryParams.value.networkType == "4G") {
        //加载4G结果
        queryPerception4gResultList(param).then(res => {
            loading.value = false
            tableData.value = res.rows;
            total.value = res.total;
        })

    }
}

// 排序
function sortChange(column, prop, order) {
    nowSortContent.value = column.prop;
    nowOrder.value = column.order;
    console.log(nowSortContent.value, nowOrder.value);
    listPerceptionTable();
}
// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 加 1 因为月份是从 0 开始的，并使用 padStart 来确保月份是两位数  
    const day = date.getDate().toString().padStart(2, '0'); // 使用 padStart 来确保日期是两位数  
    return `${year}-${month}-${day}`;
}

// 打开详情页
function showDetailDialog(rowCGI) {
    dialogTableVisible.value = true;
    chooseRowCgi.value = rowCGI;
    listDetailTable(chooseRowCgi.value);
}
// 详情页列表
async function listDetailTable(rowCGI) {
    const param = {};
    param.cgi = rowCGI;
    param.networkType = currentNetworkType.value;
    param.createStart = formatDate(detailDatePicker.value[0]);
    param.createEnd = formatDate(detailDatePicker.value[1]);
    xqLoading.value = true;
    await detailList(param).then(res => {
        xqLoading.value = false;
        detailData.value = res.data;
    })
    initChart();
}
function detailSearch() {
    listDetailTable(chooseRowCgi.value);

}

function initChart() {
    chartInstance = echarts.init(chart.value);
    drawChart();
    calculateStatistics();
}

function drawChart() {
    // const xData = detailData.value.map(item => item.createTime); // 创建时间数组  
    const xData = detailData.value.map(item => dateFormatter(null, null, item.createTime, null)); // 创建时间数组 
    const yData = detailData.value.map(item => item.perceptionScore); // 用户感知总分数组  

    const options = {
        tooltip: {
            trigger: "axis",
        },
        grid: {
            left: "5%",
            right: "15%",
            bottom: "10%",
        },
        xAxis: {
            type: 'category',
            data: xData,
        },
        yAxis: {
            type: 'value',
        },
        series: [{
            data: yData,
            type: 'line',
            smooth: true,
        }],
    };
    chartInstance.setOption(options);
}


function calculateStatistics() {
    if (detailData.value.length > 0) {
        const scores = detailData.value.map(item => item.perceptionScore);
        const startDate = new Date(detailDatePicker.value[0]);
        const endDate = new Date(detailDatePicker.value[1]);
        const diffTime = endDate - startDate;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        selectedDays.value = diffDays + 1;
        averageScore.value = scores.reduce((sum, score) => sum + score, 0) / scores.length;
        maxScore.value = Math.max(...scores);
        minScore.value = Math.min(...scores);
    } else {
        averageScore.value = 0;
        maxScore.value = 0;
        minScore.value = 0;
    }

}

function dateFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    // 创建一个新的 Date 对象
    var originalDate = new Date(cellValue);

    // 获取年、月、日、时、分、秒
    var year = originalDate.getFullYear();
    var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
    var day = ("0" + originalDate.getDate()).slice(-2);
    var hours = ("0" + originalDate.getHours()).slice(-2);
    var minutes = ("0" + originalDate.getMinutes()).slice(-2);
    var seconds = ("0" + originalDate.getSeconds()).slice(-2);

    // 格式化输出
    var formattedDateTimeString = year + "-" + month + "-" + day;
    return formattedDateTimeString;
}

// 导出
function exportData() {
    const param = {};
    param.networkType = queryParams.value.networkType
    param.county = queryParams.value.county;
    param.cgi = queryParams.value.cgi;
    param.cellName = queryParams.value.cellName;
    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
        param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
    }
    param.sortContent = nowSortContent.value;
    param.order = nowOrder.value;
    /* proxy.download("/networkPerception/exportPerceptionList", {
        ...param
    }, `用户感知_${new Date().getTime()}.xlsx`); */

    if (securityFlagConfig.configValue == "true") {
        //开启金库模式
        refExportDialog.value.show(param);
    } else {
        proxy.download("/networkPerception/exportPerceptionList", {
            ...param
        }, `用户感知_${new Date().getTime()}.xlsx`);
    }
}

function directExportData() {
    const param = {};
    param.networkType = queryParams.value.networkType
    param.county = queryParams.value.county;
    param.cgi = queryParams.value.cgi;
    param.cellName = queryParams.value.cellName;
    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
        param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
    }
    param.sortContent = nowSortContent.value;
    param.order = nowOrder.value;
    proxy.download("/networkPerception/exportPerceptionDirectList", {
        ...param
    }, `用户感知(剔除敏感数据)_${new Date().getTime()}.xlsx`);
}

function importFile() {
    importDialogVisible.value = true
}

function downloadTemplate() {
    proxy.download("/export/downloadTemplate", {
        templateName: "满意度上传表.xlsx"
    }, `满意度上传表.xlsx`);
}

function uploadSuccess(res, file, fileList) {
    importDialogVisible.value = false
    ElMessage.success(res.msg)
}

listPerceptionTable();

</script>

<style scoped>
.card-box {
    padding: 0px;
}

.card-left {
    width: 55%;
}

.title-name {
    justify-content: space-between;
    font-size: 14px;
    font-weight: bold;
}

.card-right {
    margin-left: 20px;
    width: 45%;
    /* border: 1px solid #000; */
}

.data-analyse {
    margin: 10px;
    height: 100px;
    width: 300px;

    .analyse-title {
        height: 50px;
        padding: 10px 10px 0px 10px;
        font-weight: bold;
        font-size: 14px;
    }

    .analyse-itemlist {
        height: 60px;
        width: 600px;
        margin-left: 50px;
        font-size: 14px;
        display: flex;
        flex-wrap: wrap;
    }

    .analyse-item {
        min-width: 300px;
        height: 30px;
        margin: 0px;
        padding: 0px;
        font-size: 15px;
    }
}

.download-link {
    display: block;
    padding: 5px 10px;
    color: #007bff;

    text-decoration: none;
    border-radius: 4px;
}

.el-form-item a {
    display: inline-block;
    /* 确保链接被视为块级元素的一部分，便于调整 */
    vertical-align: middle;
    text-decoration: underline;
}
</style>